//
//  LHCycleScrollView.m
//  CycleScrollViewDemo
//
//  Created by 卢浩 on 16/4/19.
//  Copyright © 2016年 卢浩. All rights reserved.
//

#import "LHCycleScrollView.h"
#import "LHNetWorkRequestManager.h"

@interface LHCycleScrollView ()<UIScrollViewDelegate>

//scrollView
@property (nonatomic,strong) UIScrollView *imgScrollView;

//pageControl
@property (nonatomic,strong) UIPageControl *imgPageControl;

//imageViewArray
@property (nonatomic,strong) NSMutableArray *imgViewArray;

//存放图片的数组
@property (nonatomic,strong) NSMutableArray *imgArray;

//当前展示的图片下标
@property (nonatomic,assign) NSInteger index;

//定时器
@property (nonatomic,strong) NSTimer *imgTimer;

//点击回调block
@property (nonatomic,copy) void(^tapBlock)(NSInteger index);

//时间间隔
@property (nonatomic,assign) NSTimeInterval interval;

@property (nonatomic,strong) NSTimer *imgArrTimer;

@end

@implementation LHCycleScrollView

//初始化方法
- (instancetype)initWithFrame:(CGRect)frame Interval:(NSTimeInterval)interval{
    self = [super initWithFrame:frame];
    if (self) {
        self.imgViewArray = [NSMutableArray array];
        self.imgArray     = [NSMutableArray array];
        
        //设置scrollView
        self.imgScrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
        //属性
        self.imgScrollView.delegate = self;
        self.imgScrollView.bounces = NO;
        self.imgScrollView.contentSize = CGSizeMake(frame.size.width * 3, frame.size.height);
        self.imgScrollView.pagingEnabled = YES;
        self.imgScrollView.showsHorizontalScrollIndicator = NO;
        self.imgScrollView.userInteractionEnabled = NO;
        [self addSubview:self.imgScrollView];
        
        for (int i = 0; i < 3; i++) {
            UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(frame.size.width * i, 0, frame.size.width, frame.size.height)];
            //添加到轮播视图,图片视图数组
            [self.imgScrollView addSubview:imageView];
            [self.imgViewArray addObject:imageView];
        }
        
        self.interval = interval;
    }
    return self;
}

//图片滚动方法
- (void)timerAction{
    [self.imgScrollView setContentOffset:CGPointMake(self.imgScrollView.frame.size.width * 2, 0) animated:YES];
    
    //方法一
    self.index = (self.index + 1) % self.imgNameArray.count;
}

//设置图片没加载完成时的默认图片,一般用于网络图片
- (void)setDefaultImg:(UIImage *)defaultImg{
    if (_defaultImg != defaultImg) {
        _defaultImg = defaultImg;
        for (int i = 0; i < 3; i++) {
            [self.imgViewArray[i] setImage:_defaultImg];
        }
    }
}

//图片名数组setter
- (void)setImgNameArray:(NSMutableArray *)imgNameArray{
    if (_imgNameArray != imgNameArray) {
        _imgNameArray = imgNameArray;
    
        //设置pageControl
        [self.imgPageControl removeFromSuperview];
        self.imgPageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, self.frame.size.height - 40, self.frame.size.width, 40)];
        [self addSubview:self.imgPageControl];
        //属性
        self.imgPageControl.currentPage = 0;
        self.imgPageControl.numberOfPages = _imgNameArray.count;
        self.imgPageControl.userInteractionEnabled = NO;
        
        self.imgArrTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(imgArrTimerAction) userInfo:nil repeats:YES];
        
        //设置图片
        for (int i = 0; i < _imgNameArray.count; i++) {
            if ([_imgNameArray[i] containsString:@"http"]) {
                [LHNetWorkRequestManager requestUrl:[NSURL URLWithString:_imgNameArray[i]] Methed:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        UIImage *image = [UIImage imageWithData:data];
                        [self.imgArray addObject:image];
                    });
                }];
            }else{
                UIImage *image = [UIImage imageNamed:_imgNameArray[i]];
                [self.imgArray addObject:image];
            }
            
        }
        
        [self.imgViewArray[1] setUserInteractionEnabled:YES];
        //点击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapCycleViewAction:)];
        [self.imgViewArray[1] addGestureRecognizer:tap];
    }
}

- (void)imgArrTimerAction{
    if (self.imgArray.count == self.imgNameArray.count) {
        [self beginTimer];
    }
}

- (void)tapCycleViewAction:(UITapGestureRecognizer *)top{
    if (self.tapBlock) {
        self.tapBlock(self.index);
    }
}

//添加Block回调
- (void)addTapBloack:(void(^)(NSInteger index))block{
    self.tapBlock = block;
}

- (void)beginTimer{
    [self.imgArrTimer invalidate];
    self.imgArrTimer = nil;
    
    self.imgScrollView.userInteractionEnabled = YES;
    
    // 初始化timer
    if (self.imgTimer) {
        [self.imgTimer invalidate];
        self.imgTimer = nil;
    }
    if (self.interval <= 0) {
        self.imgTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }else {
        self.imgTimer = [NSTimer scheduledTimerWithTimeInterval:self.interval target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    
    self.index = 0;
    [self layoutImages];
    self.imgScrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
}

#pragma mark ---- UIScrollViewDelegate

//给Index赋值
- (void)setIndex:(NSInteger)index{
    if (_index != index) {
        _index = index;
        self.imgPageControl.currentPage = self.index;
    }
}

//动画结束
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self layoutImages];
    self.imgScrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
}

static CGFloat x = 0;

//开始拖拽
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    x = scrollView.contentOffset.x;
    
    //计时器暂停
    [self.imgTimer setFireDate:[NSDate distantFuture]];
}

//已经减速
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (x > scrollView.contentOffset.x) {
        [self toLeftImage:YES Index:self.index];
    }else if(x < scrollView.contentOffset.x) {
        [self toLeftImage:NO Index:self.index];
    }
    
    //计时器开始
    [self.imgTimer setFireDate:[NSDate dateWithTimeIntervalSinceNow:2]];
}

- (void)toLeftImage:(BOOL)isleft Index:(NSInteger)index{
    if (isleft) {
        self.index = (self.index - 1 + self.imgNameArray.count) % self.imgNameArray.count;
    }else{
        self.index = (self.index + 1) % self.imgNameArray.count;
    }
    [self layoutImages];
    self.imgScrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
}

- (void)layoutImages{
    for (int i = 0; i < 3; i++) {
        [self.imgViewArray[i] setImage:self.imgArray[(self.index - 1 + i + self.imgNameArray.count) % self.imgNameArray.count]];
    }
}

@end
